package com.jsmile.cloud.accountcenter.shop.service;

import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.jsmile.cloud.accountcenter.api.enums.AccountCodeEnum;
import com.jsmile.cloud.accountcenter.api.exception.AccountException;
import com.jsmile.cloud.accountcenter.api.req.shop.ReqShopQuery;
import com.jsmile.cloud.accountcenter.api.res.ResShop;
import com.jsmile.cloud.accountcenter.shop.model.Shop;
import com.jsmile.cloud.accountcenter.shop.repo.ShopRepository;
import com.jsmile.cloud.accountcenter.shop.repo.ShopSearchRepository;
import com.jsmile.mall.api.enums.JSmileCacheEnum;
import com.jsmile.mall.api.exception.ExceptionKit;

import cn.hutool.core.bean.BeanUtil;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;

@Slf4j
@Service
@AllArgsConstructor
public class ShopApplicationService {

    private final ShopRepository shopRepository;
    private final ShopSearchRepository shopSearchRepository;

    @Cacheable(value = JSmileCacheEnum.JSmileCacheName.oneMonth, key = "'shop_'+#shopId")
    public ResShop getShop(long shopId) {
        log.info("获取店铺:{]", shopId);
        Shop shop = shopSearchRepository.getById(shopId);
        if (null == shop) {
            throw new AccountException(AccountCodeEnum.SHOP_NOT_EXISTS);
        }
        return BeanUtil.toBean(shop, ResShop.class);
    }

    @Cacheable(value = JSmileCacheEnum.JSmileCacheName.oneMonth, key = "'shop_'+#shopId")
    public ResShop getShopByUserId(long userId) {
        log.info("获取店铺:{]", userId);
        Shop shop = shopSearchRepository.findOneByUserId(userId);
        if (null == shop) {
            throw new AccountException(AccountCodeEnum.SHOP_NOT_EXISTS);
        }
        return BeanUtil.toBean(shop, ResShop.class);
    }

    public IPage<ResShop> getShopPageList(ReqShopQuery reqShopQuery) {
        ExceptionKit.checkNotNull(reqShopQuery.getCurTenantId(), "租户id不能为空!");
        log.info("店铺查询:{]", reqShopQuery);
        return shopSearchRepository.pageQuery(reqShopQuery).convert(x -> BeanUtil.toBean(x, ResShop.class));
    }

}
